<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>
  <body>
  
  </body>
  
  <script>
    /* then：Promise成功时执行，参数可为分别在fulfilled状态和rejected状态调用的两个回调函数，两回调函数的参数都为Promise执行结果 */
    new Promise((resolve, reject) => {
      if (Math.round(Math.random() * 10) > 5) {
        console.log('promise success');
        resolve(new Promise((resolve) => {
          resolve('success');
        }));
      } else {
        console.log('promise fail');
        reject('fail');
      }
    }).then((res) => {
      console.log('then fulfilled', res);
    }, (res) => {
      console.log('then rejected', res);
    });
    // 输出结果：promise success-then fulfilled success 或 promise fail-then rejected fail
    
    /* catch：then不存在第二个回调且Promise失败时执行，参数为rejected状态调用的回调函数，回调函数的参数为Promise失败执行结果，除此之外catch还会捕获then中异常 */
    new Promise((resolve, reject) => {
      console.log('promise fail');
      reject('fail');
    }).catch((res) => {
      console.log('catch', res);
    });
    // 输出结果：promise fail-catch fail
    
    /* finally：无论Promise成功或失败都执行，参数为回调函数，但finally无法知道Promise最终的状态 */
    new Promise((resolve, reject) => {
      if (Math.round(Math.random() * 10) > 5) {
        console.log('promise success');
        resolve('success');
      } else {
        console.log('promise fail');
        reject('fail');
      }
    }).finally((res) => {
      console.log('finally', res);
    });
    // 输出结果：promise success-finally undefined 或 promise fail-finally undefined
    
    /* then-catch-finally链式调用 */
    new Promise((resolve, reject) => {
      if (Math.round(Math.random() * 10) > 5) {
        console.log('promise success');
        resolve('success');
      } else {
        console.log('promise fail');
        reject('fail');
      }
    }).then((res) => {
      undefinedFunc();// then出现未定义方法，该错误会被catch捕获到吗？会，且catch捕获到后代码不继续向下执行
      console.log('then fulfilled', res);
    }, (res) => {
      console.log('then rejected', res);
      undefinedFunc();// then出现未定义方法，该错误会被catch捕获到吗？会，且catch捕获到后代码不继续向下执行
    }).catch((res) => {
      console.log('catch', res);
    }).finally((res) => {
      console.log('finally', res);
    });
    // 输出结果：
    // promise success - catch ReferenceError: undefinedFunc is not defined - finally undefined
    // promise fail - then rejected fail - catch ReferenceError: undefinedFunc is not defined - finally undefined
  </script>
</html>